package com.ptu.server.Impl;

import com.ptu.mapper.OrderMapper;
import com.ptu.server.ChartService;
import com.ptu.vo.CategorySalesVO;
import com.ptu.vo.SalesTrendVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ChartServerImpl implements ChartService {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public List<SalesTrendVO> getSalesTrend(String type) {
        // 使用LocalDate
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = type.equalsIgnoreCase("week") ?
                endDate.minusDays(7) : endDate.minusDays(30);

        // 转换为java.util.Date
        Date start = Date.from(startDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date end = Date.from(endDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

        List<Map<String, Object>> result = orderMapper.selectSalesTrend(start, end);

        return result.stream().map(map -> {
            SalesTrendVO vo = new SalesTrendVO();
            vo.setDate((String) map.get("date"));
            vo.setAmount((BigDecimal) map.get("amount"));
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<CategorySalesVO> getCategorySales() {
        List<Map<String, Object>> result = orderMapper.selectCategorySales();

        return result.stream().map(map -> {
            CategorySalesVO vo = new CategorySalesVO();
            vo.setCategory((String) map.get("category"));
            vo.setAmount((BigDecimal) map.get("amount"));
            return vo;
        }).collect(Collectors.toList());
    }
}
